# 检查是否以管理员权限运行
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "请以管理员权限运行此脚本" -ForegroundColor Red
    Write-Host "右键点击脚本，选择'以管理员身份运行'" -ForegroundColor Yellow
    exit 1
}

# 设置工作目录为脚本所在目录
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $scriptPath

# 检查 Ollama 服务状态
$ollamaService = Get-Service -Name "Ollama" -ErrorAction SilentlyContinue
if ($null -eq $ollamaService) {
    Write-Host "未找到 Ollama 服务，正在尝试启动 Ollama..." -ForegroundColor Yellow
    
    # 尝试启动 Ollama
    try {
        Start-Process "ollama" -ArgumentList "serve" -WindowStyle Hidden
        Write-Host "Ollama 服务已启动" -ForegroundColor Green
        # 等待服务启动
        Start-Sleep -Seconds 5
    }
    catch {
        Write-Host "无法启动 Ollama 服务，请确保 Ollama 已正确安装" -ForegroundColor Red
        exit 1
    }
}
elseif ($ollamaService.Status -ne "Running") {
    Write-Host "正在启动 Ollama 服务..." -ForegroundColor Yellow
    Start-Service "Ollama"
    Start-Sleep -Seconds 5
}

# 检查 Python 环境
try {
    $pythonVersion = python --version
    Write-Host "Python 版本: $pythonVersion" -ForegroundColor Green
}
catch {
    Write-Host "未找到 Python，请确保 Python 已正确安装并添加到系统环境变量" -ForegroundColor Red
    exit 1
}

# 检查并创建虚拟环境
if (-not (Test-Path "venv")) {
    Write-Host "正在创建虚拟环境..." -ForegroundColor Yellow
    python -m venv venv
}

# 激活虚拟环境并确保使用虚拟环境的 Python
Write-Host "正在激活虚拟环境..." -ForegroundColor Yellow
.\venv\Scripts\Activate.ps1
$env:PATH = "$scriptPath\venv\Scripts;$env:PATH"

# 升级 pip
Write-Host "正在升级 pip..." -ForegroundColor Yellow
python -m pip install --upgrade pip

# 安装依赖
Write-Host "正在安装依赖..." -ForegroundColor Yellow
# 首先安装基本依赖
python -m pip install requests fastapi uvicorn pydantic

# 然后安装 requirements.txt 中的其他依赖
if (Test-Path "requirements.txt") {
    python -m pip install -r requirements.txt
}

# 验证关键依赖是否安装成功
try {
    python -c "import requests; import fastapi; import uvicorn; import pydantic"
    Write-Host "依赖安装成功" -ForegroundColor Green
}
catch {
    Write-Host "依赖安装失败，请检查错误信息：" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    exit 1
}

# 检查模型是否已安装
Write-Host "检查模型状态..." -ForegroundColor Yellow
try {
    $modelCheck = Invoke-RestMethod -Uri "http://localhost:11434/api/tags" -Method Get
    if ($modelCheck.models.name -notcontains "qwen3:8b") {
        Write-Host "正在下载 qwen3:8b 模型..." -ForegroundColor Yellow
        ollama pull qwen3:8b
    }
    else {
        Write-Host "模型已安装" -ForegroundColor Green
    }
}
catch {
    Write-Host "检查模型状态失败，请确保 Ollama 服务正在运行" -ForegroundColor Red
    exit 1
}

# 启动 Python 服务
Write-Host "正在启动智能代理服务..." -ForegroundColor Yellow
try {
    Start-Process python -ArgumentList "run_agent.py" -NoNewWindow -WorkingDirectory $scriptPath
    Start-Sleep -Seconds 2  # 等待服务启动
    
    # 验证服务是否成功启动
    $serviceCheck = Invoke-RestMethod -Uri "http://localhost:8000/v1/model/status" -Method Get -ErrorAction SilentlyContinue
    if ($serviceCheck) {
        Write-Host "智能代理服务启动成功" -ForegroundColor Green
    }
}
catch {
    Write-Host "启动智能代理服务失败：" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    exit 1
}

Write-Host "`n所有服务已启动！" -ForegroundColor Green
Write-Host "服务状态：" -ForegroundColor Cyan
Write-Host "1. Ollama 服务: 运行中" -ForegroundColor Green
Write-Host "2. Python 虚拟环境: 已激活" -ForegroundColor Green
Write-Host "3. 智能代理服务: 已启动" -ForegroundColor Green
Write-Host "`n按 Ctrl+C 可以停止所有服务" -ForegroundColor Yellow

# 保持脚本运行以维持服务
try {
    while ($true) {
        Start-Sleep -Seconds 1
    }
}
finally {
    # 清理进程
    Write-Host "`n正在停止服务..." -ForegroundColor Yellow
    Get-Process python | Where-Object { $_.CommandLine -like "*run_agent.py*" } | Stop-Process -Force
    Get-Process ollama | Stop-Process -Force
    Write-Host "所有服务已停止" -ForegroundColor Green
} 